<?php
namespace app\mingteng\logic;

use app\home\logic\CartLogic;
use think\Model;
use think\Db;

class OrderLogic extends Model{
    /**
     * @param array $condition  搜索条件
     * @param string $order   排序方式
     * @param int $start    limit开始行
     * @param int $page_size  获取数量
     */
    public function getOrderList($condition,$order='',$start=0,$page_size=20){
        $res = M('order')->where($condition)->limit("$start,$page_size")->order($order)->select();
        return $res;
    }


    /**
     * 获取订单商品详情  2017-4-28 lxl 改
     * @param $order_id
     * @param string $is_send
     * @return mixed
     */
    public function getOrderGoods($order_id,$is_send =''){
        if($is_send){
            $where=" and o.is_send < $is_send";
        }
        $sql = "SELECT g.*,o.*,(o.goods_num * o.goods_price) AS goods_total FROM __PREFIX__order_goods o ".
            "LEFT JOIN __PREFIX__goods g ON o.goods_id = g.goods_id WHERE o.order_id = $order_id ".$where;
        $res = DB::query($sql);
        return $res;
    }


    /*
     * 获取订单信息
     */
    public function getOrderInfo($order_id)
    {
        //  订单总金额查询语句		
        $order = M('shop_order')->where("order_id = $order_id")->find();
        return $order;
    }

    /*
     * 根据商品型号获取商品
     */
    public function get_spec_goods($goods_id_arr){
    	if(!is_array($goods_id_arr)) return false;
    		foreach($goods_id_arr as $key => $val)
    		{
    			$arr = array();
    			$goods = M('goods')->where("goods_id = $key")->find();
    			$arr['goods_id'] = $key; // 商品id
    			$arr['goods_name'] = $goods['goods_name'];
    			$arr['goods_sn'] = $goods['goods_sn'];
    			$arr['market_price'] = $goods['market_price'];
    			$arr['goods_price'] = $goods['shop_price'];
    			$arr['cost_price'] = $goods['cost_price'];
    			$arr['member_goods_price'] = $goods['shop_price'];
    			foreach($val as $k => $v)
    			{
    				$arr['goods_num'] = $v['goods_num']; // 购买数量
    				// 如果这商品有规格
    				if($k != 'key')
    				{
    					$arr['spec_key'] = $k;
    					$spec_goods = M('spec_goods_price')->where("goods_id = $key and `key` = '{$k}'")->find();
    					$arr['spec_key_name'] = $spec_goods['key_name'];
    					$arr['member_goods_price'] = $arr['goods_price'] = $spec_goods['price'];
    					$arr['sku'] = $spec_goods['sku']; // 参考 sku  http://www.zhihu.com/question/19841574
    				}
    				$order_goods[] = $arr;
    			}
    		}
    		return $order_goods;	
    }

    /*
     * 订单操作记录
     */
    public function orderActionLog($order_id,$action,$note=''){    	
        $order = M('order')->where(array('order_id'=>$order_id))->find();
        $data['order_id'] = $order_id;
        $data['action_user'] = session('admin_id');
        $data['action_note'] = $note;
        $data['order_status'] = $order['order_status'];
        $data['log_time'] = time();
        $data['status_desc'] = $action;        
        return M('order_action')->add($data);//订单操作记录
    }

    /*
     * 获取订单商品总价格
     */
    public function getGoodsAmount($order_id){
        $sql = "SELECT SUM(goods_num * goods_price) AS goods_amount FROM __PREFIX__order_goods WHERE order_id = {$order_id}";
        $res = DB::query($sql);
        return $res[0]['goods_amount'];
    }

    /**
     * 得到发货单流水号
     */
    public function get_delivery_sn()
    {
//        /* 选择一个随机的方案 */send_http_status('310');
		mt_srand((double) microtime() * 1000000);
        return date('YmdHi') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    /*
     * 获取当前可操作的按钮
     */
    public function getOrderButton($order_status){

    	$os = $order_status;//订单状态

        $btn = array();
        if($os == 0){ //待付款
            $btn['invalid'] = '作废';
        }
        if($os == 1){ //待配送
            $btn['delivery'] = '发货';
            $btn['win'] = '已自取';
        }
        return $btn;
    }
    
    public function orderProcessHandle($order_id,$act){
    	$updata = array();
    	switch ($act){
    		case 'invalid': //作废
    			$updata['order_status'] = -1;
    			break;
            case 'delivery': //发货
                $updata['order_status'] = 2;
                $updata['delivery_time'] = time();
                break;
            case 'win': //发货
                $updata['order_status'] = 3;
                $updata['delivery_time'] = time();
                $updata['turnover_time'] = time();
                break;
    		default:
    			return true;
    	}
    	return M('shop_order')->where("order_id=$order_id")->save($updata);//改变订单状态
    }

    /**
 * 删除订单
 */
    function delOrder($order_id){
        $a = M('order')->where(array('order_id'=>$order_id))->delete();
        $b = M('order_goods')->where(array('order_id'=>$order_id))->delete();
        return $a && $b;
    }

	/**
	 * 当订单里商品都退货完成，将订单状态改成关闭
	 * @param $order_id
	 */
	function closeOrderByReturn($order_id)
	{
		$order_goods_list = Db::name('order_goods')->where(['order_id' => $order_id])->select();
		$order_goods_count = count($order_goods_list);
		$order_goods_return_count = 0;//退货个数
		for ($i = 0; $i < $order_goods_count; $i++) {
			if ($order_goods_list[$i]['is_send'] == 3) {
				$order_goods_return_count++;
			}
		}
		if ($order_goods_count == $order_goods_return_count) {
			Db::name('order')->where(['order_id' => $order_id])->update(['order_status' => 5]);
		}
	}

    /**
     * 更改售后状态
     * @author lxl
     * @time 2017-5-10
     * @param $return_id    退货ID
     * @param $order_id    订单ID
     * @param int $is_end  订单商品状态
     * @return $this
     */
    public function alterReturnGoodsStatus($return_id,$order_id,$is_end=3){
        $update = M('return_goods')->where('id',$return_id)->update(['status'=>$is_end]);  //要更新退货单状态
        if($update) {
            $return_goods = M('return_goods')->where('id', $return_id)->find();
            $res = M('order_goods')->where(array(
                'order_id' => $order_id,
                'goods_id' => $return_goods['goods_id'],
                'spec_key' => $return_goods['spec_key']))->update(['is_send' => $is_end]);  //订单商品改为已退货
            return $res;
        }
    }

    /**
     * 售后通过后改变库存，根据不同的规格，商品活动修改对应的库存
     * @author lxl
     * @time 2017-5-10
     * @param $order_id 订单ID
     * @param $goods_id 商品ID
     */
    public function alterReturnGoodsInventory($order_id,$goods_id){
        $spec_goods=M('order_goods')->field('goods_num,spec_key,prom_type,prom_id')
            ->where(['order_id' =>$order_id,'goods_id'=>$goods_id])
            ->find(); //查找购买数量和购买规格

        $where = ['id' => $spec_goods['prom_id'] , 'goods_id' => $goods_id];
        if($spec_goods['prom_type']==1){    //是抢购的
            M('flash_sale')->where($where)->setDec('buy_num', $spec_goods['goods_num']);
        }
        if($spec_goods['prom_type']==2){    //是团购的
            M('group_buy')->where($where)->setDec('store_count', $spec_goods['goods_num']);
        }else{  //普通订单
            if(!empty($spec_goods['spec_key'])){
                M('spec_goods_price')
                    ->where("goods_id = $goods_id and `key` = '{$spec_goods['spec_key']}'")
                    ->setInc('store_count', $spec_goods['goods_num']);//有规格则增加商品对应规格的库存
            }else{
                M('goods')->where("goods_id = $goods_id")->setInc('store_count', $spec_goods['goods_num']);//没有规格则增加商品库存
            }
        }

    }

}